/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.broiler_pro.modular.broilerproduct.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.barn.modular.barn.mapper.BizBarnMapper;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.entity.BizBroilerProduct;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.entity.BroilerProductView;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.mapper.BizBroilerProductMapper;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.mapper.BroilerProductViewMapper;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.param.BizBroilerProductAddParam;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.param.BizBroilerProductEditParam;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.param.BizBroilerProductIdParam;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.param.BizBroilerProductPageParam;
import vip.xiaonuo.broiler_pro.modular.broilerproduct.service.BizBroilerProductService;
import vip.xiaonuo.broiler_stoke.modular.broilerstocks.entity.BizBroilerStocks;
import vip.xiaonuo.broiler_stoke.modular.broilerstocks.mapper.BizBroilerStocksMapper;
import vip.xiaonuo.column.modular.column.entity.BizColumn;
import vip.xiaonuo.column.modular.column.mapper.BizColumnMapper;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 肉鸡产出Service接口实现类
 *
 * @author zyb
 * @date  2023/12/19 12:54
 **/
@Service
public class BizBroilerProductServiceImpl extends ServiceImpl<BizBroilerProductMapper, BizBroilerProduct> implements BizBroilerProductService {

    @Resource
    private BizColumnMapper columnMapper;

    @Resource
    private BizBarnMapper barnMapper;

    @Resource
    private BizBroilerStocksMapper broilerStocksMapper;

    @Resource
    private BroilerProductViewMapper broilerProductViewMapper;

    private static final String BROILER_TYPE = "肉鸡";
    private static final String LAYER_TYPE = "蛋鸡";
    private static final String ERROE_TYPE = "异常类型";

    @Override
    public Page<BroilerProductView> page(BizBroilerProductPageParam bizBroilerProductPageParam) {
        QueryWrapper<BroilerProductView> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizBroilerProductPageParam.getBarnId())) {
            queryWrapper.lambda().eq(BroilerProductView::getBarnId, bizBroilerProductPageParam.getBarnId());
        }
        if(ObjectUtil.isNotEmpty(bizBroilerProductPageParam.getStartSlaughterDate()) && ObjectUtil.isNotEmpty(bizBroilerProductPageParam.getEndSlaughterDate())) {
            queryWrapper.lambda().between(BroilerProductView::getSlaughterDate, bizBroilerProductPageParam.getStartSlaughterDate(), bizBroilerProductPageParam.getEndSlaughterDate());
        }
        if(ObjectUtil.isNotEmpty(bizBroilerProductPageParam.getBroilerType())) {
            queryWrapper.lambda().eq(BroilerProductView::getBroilerType, bizBroilerProductPageParam.getBroilerType());
        }
        if(ObjectUtil.isAllNotEmpty(bizBroilerProductPageParam.getSortField(), bizBroilerProductPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizBroilerProductPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizBroilerProductPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizBroilerProductPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BroilerProductView::getId);
        }
        return broilerProductViewMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizBroilerProductAddParam bizBroilerProductAddParam) {
        BizBroilerProduct bizBroilerProduct = BeanUtil.toBean(bizBroilerProductAddParam, BizBroilerProduct.class);
        Integer quantity = bizBroilerProductAddParam.getQuantity();
        BigDecimal totalWeight = bizBroilerProduct.getTotalWeight();
        // 计算平均重量
        BigDecimal averageWeight = totalWeight.divide(new BigDecimal(quantity), 2, RoundingMode.HALF_UP);
        bizBroilerProduct.setAverageWeight(averageWeight);
        this.save(bizBroilerProduct);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizBroilerProductEditParam bizBroilerProductEditParam) {
        BizBroilerProduct bizBroilerProduct = this.queryEntity(bizBroilerProductEditParam.getId());
        BeanUtil.copyProperties(bizBroilerProductEditParam, bizBroilerProduct);
        this.updateById(bizBroilerProduct);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizBroilerProductIdParam> bizBroilerProductIdParamList) {
        // 级联更新肉鸡库存的数量、总重量、平均重量
        LambdaQueryWrapper<BizBroilerStocks> queryWrapper = new LambdaQueryWrapper<>();
        for (BizBroilerProductIdParam bizBroilerProductIdParam : bizBroilerProductIdParamList) {
            BizBroilerProduct bizBroilerProduct = this.queryEntity(bizBroilerProductIdParam.getId());

            String barnId = bizBroilerProduct.getBarnId();
            String broilerType = bizBroilerProduct.getBroilerType();
            queryWrapper.eq(BizBroilerStocks::getBarnId, barnId).eq(BizBroilerStocks::getType, broilerType);
            BizBroilerStocks bizBroilerStocks = broilerStocksMapper.selectOne(queryWrapper);

            // 计算平均重量
            Integer quantity = bizBroilerStocks.getQuantity() - bizBroilerProduct.getQuantity();
            BigDecimal totalWeight = bizBroilerStocks.getTotalWeight().subtract(bizBroilerProduct.getTotalWeight());
            BigDecimal averageWeight = totalWeight.divide(new BigDecimal(quantity), 2, RoundingMode.HALF_UP);

            bizBroilerStocks.setQuantity(quantity);
            bizBroilerStocks.setTotalWeight(totalWeight);
            bizBroilerStocks.setAverageWeight(averageWeight);

            broilerStocksMapper.updateById(bizBroilerStocks);
        }
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizBroilerProductIdParamList, BizBroilerProductIdParam::getId));
    }

    @Override
    public BizBroilerProduct detail(BizBroilerProductIdParam bizBroilerProductIdParam) {
        return this.queryEntity(bizBroilerProductIdParam.getId());
    }

    @Override
    public BizBroilerProduct queryEntity(Integer id) {
        BizBroilerProduct bizBroilerProduct = this.getById(id);
        if(ObjectUtil.isEmpty(bizBroilerProduct)) {
            throw new CommonException("肉鸡产出不存在，id值为：{}", id);
        }
        return bizBroilerProduct;
    }

    @Override
    public String getBroilerTypeByColumnId(String columnId) {
        BizColumn column = columnMapper.selectById(columnId);
        if (ObjectUtil.isNotEmpty(column)){
            String sign = column.getSign();
            if(BROILER_TYPE.equals(sign)){
                return column.getTypeId();
            }
            else if(LAYER_TYPE.equals(sign)){
                throw new CommonException("警告！该栏区不是肉鸡栏区，请重新选择！");
            }
        }
        else{
            throw new CommonException("未选择栏区信息！");
        }
        return ERROE_TYPE;
    }
}
